package com.cyy.demo.test;


/**
 * 1 无论是修饰方法还是修饰代码块都是 对象锁,当一个线程访问一个带synchronized方法时，由于对象锁的存在，所有加synchronized的方法都不能被访问（前提是在多个线程调用的是同一个对象实例中的方法）
 * 2 无论是修饰静态方法还是锁定某个对象,都是 类锁.一个class其中的静态方法和静态变量在内存中只会加载和初始化一份，所以，一旦一个静态的方法被申明为synchronized，此类的所有的实例化对象在调用该方法时，共用同一把锁，称之为类锁。
 */
public class DeadLock {

    User1 user1 = new User1();
    User2 user2 = new User2();

    public static void main(String[] args) {
        MyThread1 myThread1 = new MyThread1();
        Thread t1 = new Thread(myThread1);
        Thread t2 = new Thread(myThread1);
        t1.start();
        t2.start();
    }

}

class User1 {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void hello(int i) {
        System.out.println("User1>>>hello" + i);
    }
}

class User2 {
    private String username;
    private String password;

    public void hello(int i) {
        System.out.println("User2>>>hello" + i);
    }
}


/**
 * 线程类
 */
class MyThread1 implements Runnable {
    User1 user1 = new User1();
    User2 user2 = new User2();

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
//            synchronized (User1.class) {
            synchronized (user1) {
                System.out.println("锁住user1");
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                synchronized (User2.class) {
                synchronized (user2) {
                    System.out.println("锁住user2");
                }

            }

//            synchronized (User2.class) {
            synchronized (user2) {
                System.out.println("锁住user2");
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                synchronized (User1.class) {
                synchronized (user1) {
                    System.out.println("锁住user1");
                }
            }
        }
    }


}
